package bll

import (
	"fmt"

	. "7qule.com/sd3/CrossServer/src/bll/kuangzhan/model"
	"7qule.com/sd3/CrossServer/src/common/onlinelog"
	"7qule.com/sd3/CrossServer/src/common/systemConstant"
	"public.com/goutil/syncUtil"
)

type globalKuangzhanPlayer struct {
	// 用户占领镖局的信息
	data map[string]*GlobalKuangzhan

	// 数据同步对象
	dataLock *syncUtil.RWLocker
}

var GlobalKuangzhanPlayer = &globalKuangzhanPlayer{
	dataLock: syncUtil.NewRWLocker(),
}

//
// InitData
// @Description: 初始化数据
// @receiver this
//
func (this *globalKuangzhanPlayer) InitData() {
	layerMap := GlobalKuangzhanBll.GetData()

	tempMap := make(map[string]*GlobalKuangzhan)
	for _, layer := range layerMap {
		for _, position := range layer.GetData() {
			if position.PlayerId != "" {
				tempMap[position.PlayerId] = position
			}
		}
	}
	this.data = tempMap
	return
}

//
// GetPlayer
// @Description: 获取节点
// @receiver this
// @param playerId 用户id
// @return result 节点信息
// @return exist 用户是否存在
//
func (this *globalKuangzhanPlayer) GetPlayer(playerId string) (result *GlobalKuangzhan, exist bool) {
	if isOk, prevStack, currStack := this.dataLock.RLock(systemConstant.DefaultLockTime); isOk == false {
		errMsg := fmt.Sprintf("Lock timeout! \n上一个堆栈:\n%s  \n当前堆栈:\n%s", prevStack, currStack)
		onlinelog.ErrorLog(errMsg)
		panic(errMsg)
	}
	defer this.dataLock.RUnlock()

	result, exist = this.data[playerId]
	return
}

//
// AddPlayer
// @Description: 添加用户
// @receiver this
// @param playerId 用户id
// @param data 节点信息
//
func (this *globalKuangzhanPlayer) AddPlayer(data *GlobalKuangzhan) {
	if isOk, prevStack, currStack := this.dataLock.Lock(systemConstant.DefaultLockTime); isOk == false {
		errMsg := fmt.Sprintf("Lock timeout! \n上一个堆栈:\n%s  \n当前堆栈:\n%s", prevStack, currStack)
		onlinelog.ErrorLog(errMsg)
		panic(errMsg)
	}
	defer this.dataLock.Unlock()

	this.data[data.PlayerId] = data
}

//
// DeletePlayer
// @Description: 删除用户
// @receiver this
// @param playerId 用户id
//
func (this *globalKuangzhanPlayer) DeletePlayer(playerId string) {
	if isOk, prevStack, currStack := this.dataLock.Lock(systemConstant.DefaultLockTime); isOk == false {
		errMsg := fmt.Sprintf("Lock timeout! \n上一个堆栈:\n%s  \n当前堆栈:\n%s", prevStack, currStack)
		onlinelog.ErrorLog(errMsg)
		panic(errMsg)
	}
	defer this.dataLock.Unlock()

	delete(this.data, playerId)
}
